<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="language" content="en" />
        <link href="./assets/ffd55088/css/bootstrap.css" rel="stylesheet">
<link href="./assets/5cf9384a/solarized_light.css" rel="stylesheet">
<link href="./assets/6c54116e/style.css" rel="stylesheet">
<script src="./assets/a44cef0f/jquery.js"></script>
<script src="./assets/ffd55088/js/bootstrap.js"></script>
<script src="./assets/8ac4e28a/jssearch.js"></script>    <title>Views - Application Structure - The Definitive Guide to Yii 2.0</title>
</head>
<body>

<div class="wrap">
    <nav id="w1403" class="navbar-inverse navbar-fixed-top navbar" role="navigation"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#w1403-collapse"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span></button><a class="navbar-brand" href="./index.html">The Definitive Guide to Yii 2.0</a></div><div id="w1403-collapse" class="collapse navbar-collapse"><ul id="w1404" class="navbar-nav nav"><li><a href="./index.html">Class reference</a></li>
<li class="dropdown"><a class="dropdown-toggle" href="#" data-toggle="dropdown">Extensions <b class="caret"></b></a><ul id="w1405" class="dropdown-menu"><li><a href="./ext-apidoc-index.html" tabindex="-1">apidoc</a></li>
<li><a href="./ext-authclient-index.html" tabindex="-1">authclient</a></li>
<li><a href="./ext-bootstrap-index.html" tabindex="-1">bootstrap</a></li>
<li><a href="./ext-codeception-index.html" tabindex="-1">codeception</a></li>
<li><a href="./ext-debug-index.html" tabindex="-1">debug</a></li>
<li><a href="./ext-elasticsearch-index.html" tabindex="-1">elasticsearch</a></li>
<li><a href="./ext-faker-index.html" tabindex="-1">faker</a></li>
<li><a href="./ext-gii-index.html" tabindex="-1">gii</a></li>
<li><a href="./ext-imagine-index.html" tabindex="-1">imagine</a></li>
<li><a href="./ext-jui-index.html" tabindex="-1">jui</a></li>
<li><a href="./ext-mongodb-index.html" tabindex="-1">mongodb</a></li>
<li><a href="./ext-redis-index.html" tabindex="-1">redis</a></li>
<li><a href="./ext-smarty-index.html" tabindex="-1">smarty</a></li>
<li><a href="./ext-sphinx-index.html" tabindex="-1">sphinx</a></li>
<li><a href="./ext-swiftmailer-index.html" tabindex="-1">swiftmailer</a></li>
<li><a href="./ext-twig-index.html" tabindex="-1">twig</a></li></ul></li>
<li><a href="./guide-README.html">Guide</a></li></ul><div class="navbar-form navbar-left" role="search">
  <div class="form-group">
    <input id="searchbox" type="text" class="form-control" placeholder="Search">
  </div>
</div>
</div></nav>
    <div id="search-resultbox" style="display: none;" class="modal-content">
        <ul id="search-results">
        </ul>
    </div>

    
<div class="row">
    <div class="col-md-2">
                <div id="navigation" class="list-group"><a class="list-group-item" href="#navigation-1387" data-toggle="collapse" data-parent="#navigation">Introduction <b class="caret"></b></a><div id="navigation-1387" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-intro-yii.html">About Yii</a>
<a class="list-group-item" href="./guide-intro-upgrade-from-v1.html">Upgrading from Version 1.1</a></div>
<a class="list-group-item" href="#navigation-1388" data-toggle="collapse" data-parent="#navigation">Getting Started <b class="caret"></b></a><div id="navigation-1388" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-start-installation.html">Installing Yii</a>
<a class="list-group-item" href="./guide-start-workflow.html">Running Applications</a>
<a class="list-group-item" href="./guide-start-hello.html">Saying Hello</a>
<a class="list-group-item" href="./guide-start-forms.html">Working with Forms</a>
<a class="list-group-item" href="./guide-start-databases.html">Working with Databases</a>
<a class="list-group-item" href="./guide-start-gii.html">Generating Code with Gii</a>
<a class="list-group-item" href="./guide-start-looking-ahead.html">Looking Ahead</a></div>
<a class="list-group-item active" href="#navigation-1389" data-toggle="collapse" data-parent="#navigation">Application Structure <b class="caret"></b></a><div id="navigation-1389" class="submenu panel-collapse collapse in"><a class="list-group-item" href="./guide-structure-overview.html">Overview</a>
<a class="list-group-item" href="./guide-structure-entry-scripts.html">Entry Scripts</a>
<a class="list-group-item" href="./guide-structure-applications.html">Applications</a>
<a class="list-group-item" href="./guide-structure-application-components.html">Application Components</a>
<a class="list-group-item" href="./guide-structure-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-structure-models.html">Models</a>
<a class="list-group-item active" href="./guide-structure-views.html">Views</a>
<a class="list-group-item" href="./guide-structure-modules.html">Modules</a>
<a class="list-group-item" href="./guide-structure-filters.html">Filters</a>
<a class="list-group-item" href="./guide-structure-widgets.html">Widgets</a>
<a class="list-group-item" href="./guide-structure-assets.html">Assets</a>
<a class="list-group-item" href="./guide-structure-extensions.html">Extensions</a></div>
<a class="list-group-item" href="#navigation-1390" data-toggle="collapse" data-parent="#navigation">Handling Requests <b class="caret"></b></a><div id="navigation-1390" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-runtime-overview.html">Overview</a>
<a class="list-group-item" href="./guide-runtime-bootstrapping.html">Bootstrapping</a>
<a class="list-group-item" href="./guide-runtime-routing.html">Routing and URL Creation</a>
<a class="list-group-item" href="./guide-runtime-requests.html">Requests</a>
<a class="list-group-item" href="./guide-runtime-responses.html">Responses</a>
<a class="list-group-item" href="./guide-runtime-sessions-cookies.html">Sessions and Cookies</a>
<a class="list-group-item" href="./guide-runtime-handling-errors.html">Handling Errors</a>
<a class="list-group-item" href="./guide-runtime-logging.html">Logging</a></div>
<a class="list-group-item" href="#navigation-1391" data-toggle="collapse" data-parent="#navigation">Key Concepts <b class="caret"></b></a><div id="navigation-1391" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-concept-components.html">Components</a>
<a class="list-group-item" href="./guide-concept-properties.html">Properties</a>
<a class="list-group-item" href="./guide-concept-events.html">Events</a>
<a class="list-group-item" href="./guide-concept-behaviors.html">Behaviors</a>
<a class="list-group-item" href="./guide-concept-configurations.html">Configurations</a>
<a class="list-group-item" href="./guide-concept-aliases.html">Aliases</a>
<a class="list-group-item" href="./guide-concept-autoloading.html">Class Autoloading</a>
<a class="list-group-item" href="./guide-concept-service-locator.html">Service Locator</a>
<a class="list-group-item" href="./guide-concept-di-container.html">Dependency Injection Container</a></div>
<a class="list-group-item" href="#navigation-1392" data-toggle="collapse" data-parent="#navigation">Working with Databases <b class="caret"></b></a><div id="navigation-1392" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-db-dao.html">Data Access Objects</a>
<a class="list-group-item" href="./guide-db-query-builder.html">Query Builder</a>
<a class="list-group-item" href="./guide-db-active-record.html">Active Record</a>
<a class="list-group-item" href="./guide-db-migrations.html">Migrations</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-sphinx/blob/master/docs/guide/README.md">Sphinx</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-redis/blob/master/docs/guide/README.md">Redis</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-mongodb/blob/master/docs/guide/README.md">MongoDB</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/README.md">ElasticSearch</a></div>
<a class="list-group-item" href="#navigation-1393" data-toggle="collapse" data-parent="#navigation">Getting Data from Users <b class="caret"></b></a><div id="navigation-1393" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-input-forms.html">Creating Forms</a>
<a class="list-group-item" href="./guide-input-validation.html">Validating Input</a>
<a class="list-group-item" href="./guide-input-file-upload.html">Uploading Files</a>
<a class="list-group-item" href="./guide-input-tabular-input.html">Collecting Tabular Input</a>
<a class="list-group-item" href="./guide-input-multiple-models.html">Getting Data for Multiple Models</a></div>
<a class="list-group-item" href="#navigation-1394" data-toggle="collapse" data-parent="#navigation">Displaying Data <b class="caret"></b></a><div id="navigation-1394" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-output-formatting.html">Data Formatting</a>
<a class="list-group-item" href="./guide-output-pagination.html">Pagination</a>
<a class="list-group-item" href="./guide-output-sorting.html">Sorting</a>
<a class="list-group-item" href="./guide-output-data-providers.html">Data Providers</a>
<a class="list-group-item" href="./guide-output-data-widgets.html">Data Widgets</a>
<a class="list-group-item" href="./guide-output-client-scripts.html">Working with Client Scripts</a>
<a class="list-group-item" href="./guide-output-theming.html">Theming</a></div>
<a class="list-group-item" href="#navigation-1395" data-toggle="collapse" data-parent="#navigation">Security <b class="caret"></b></a><div id="navigation-1395" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-security-overview.html">Overview</a>
<a class="list-group-item" href="./guide-security-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-security-authorization.html">Authorization</a>
<a class="list-group-item" href="./guide-security-passwords.html">Working with Passwords</a>
<a class="list-group-item" href="./guide-security-cryptography.html">Cryptography</a>
<a class="list-group-item" href="./guide-structure-views.html#security">Views security</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-authclient/blob/master/docs/guide/README.md">Auth Clients</a>
<a class="list-group-item" href="./guide-security-best-practices.html">Best Practices</a></div>
<a class="list-group-item" href="#navigation-1396" data-toggle="collapse" data-parent="#navigation">Caching <b class="caret"></b></a><div id="navigation-1396" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-caching-overview.html">Overview</a>
<a class="list-group-item" href="./guide-caching-data.html">Data Caching</a>
<a class="list-group-item" href="./guide-caching-fragment.html">Fragment Caching</a>
<a class="list-group-item" href="./guide-caching-page.html">Page Caching</a>
<a class="list-group-item" href="./guide-caching-http.html">HTTP Caching</a></div>
<a class="list-group-item" href="#navigation-1397" data-toggle="collapse" data-parent="#navigation">RESTful Web Services <b class="caret"></b></a><div id="navigation-1397" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-rest-quick-start.html">Quick Start</a>
<a class="list-group-item" href="./guide-rest-resources.html">Resources</a>
<a class="list-group-item" href="./guide-rest-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-rest-routing.html">Routing</a>
<a class="list-group-item" href="./guide-rest-response-formatting.html">Response Formatting</a>
<a class="list-group-item" href="./guide-rest-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-rest-rate-limiting.html">Rate Limiting</a>
<a class="list-group-item" href="./guide-rest-versioning.html">Versioning</a>
<a class="list-group-item" href="./guide-rest-error-handling.html">Error Handling</a></div>
<a class="list-group-item" href="#navigation-1398" data-toggle="collapse" data-parent="#navigation">Development Tools <b class="caret"></b></a><div id="navigation-1398" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-debug/blob/master/docs/guide/README.md">Debug Toolbar and Debugger</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md">Generating Code using Gii</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-apidoc">Generating API Documentation</a></div>
<a class="list-group-item" href="#navigation-1399" data-toggle="collapse" data-parent="#navigation">Testing <b class="caret"></b></a><div id="navigation-1399" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-test-overview.html">Overview</a>
<a class="list-group-item" href="./guide-test-environment-setup.html">Testing environment setup</a>
<a class="list-group-item" href="./guide-test-unit.html">Unit Tests</a>
<a class="list-group-item" href="./guide-test-functional.html">Functional Tests</a>
<a class="list-group-item" href="./guide-test-acceptance.html">Acceptance Tests</a>
<a class="list-group-item" href="./guide-test-fixtures.html">Fixtures</a></div>
<a class="list-group-item" href="#navigation-1400" data-toggle="collapse" data-parent="#navigation">Special Topics <b class="caret"></b></a><div id="navigation-1400" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md">Advanced Project Template</a>
<a class="list-group-item" href="./guide-tutorial-start-from-scratch.html">Building Application from Scratch</a>
<a class="list-group-item" href="./guide-tutorial-console.html">Console Commands</a>
<a class="list-group-item" href="./guide-tutorial-core-validators.html">Core Validators</a>
<a class="list-group-item" href="./guide-tutorial-i18n.html">Internationalization</a>
<a class="list-group-item" href="./guide-tutorial-mailing.html">Mailing</a>
<a class="list-group-item" href="./guide-tutorial-performance-tuning.html">Performance Tuning</a>
<a class="list-group-item" href="./guide-tutorial-shared-hosting.html">Shared Hosting Environment</a>
<a class="list-group-item" href="./guide-tutorial-template-engines.html">Template Engines</a>
<a class="list-group-item" href="./guide-tutorial-yii-integration.html">Working with Third-Party Code</a></div>
<a class="list-group-item" href="#navigation-1401" data-toggle="collapse" data-parent="#navigation">Widgets <b class="caret"></b></a><div id="navigation-1401" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-bootstrap/blob/master/docs/guide/README.md">Bootstrap Widgets</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-jui/blob/master/docs/guide/README.md">jQuery UI Widgets</a></div>
<a class="list-group-item" href="#navigation-1402" data-toggle="collapse" data-parent="#navigation">Helpers <b class="caret"></b></a><div id="navigation-1402" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-helper-overview.html">Overview</a>
<a class="list-group-item" href="./guide-helper-array.html">ArrayHelper</a>
<a class="list-group-item" href="./guide-helper-html.html">Html</a>
<a class="list-group-item" href="./guide-helper-url.html">Url</a></div></div>    </div>
    <div class="col-md-9 guide-content" role="main">
        <h1>Views <span id="views"></span><a href="#views" class="hashlink">&para;</a></h1>
<div class="toc"><ol><li><a href="#creating-views">Creating Views</a></li>
<li><a href="#rendering-views">Rendering Views</a></li>
<li><a href="#layouts">Layouts</a></li>
<li><a href="#using-view-components">Using View Components</a></li>
<li><a href="#view-events">View Events</a></li>
<li><a href="#rendering-static-pages">Rendering Static Pages</a></li>
<li><a href="#best-practices">Best Practices</a></li></ol></div>
<p>Views are part of the <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> architecture.
They are code responsible for presenting data to end users. In a Web application, views are usually created
in terms of <em>view templates</em> which are PHP script files containing mainly HTML code and presentational PHP code.
They are managed by the <a href="./yii-web-view.html">view</a> <a href="guide-structure-application-components.html">application component</a> which provides commonly used methods
to facilitate view composition and rendering. For simplicity, we often call view templates or view template files
as views.</p>
<h2>Creating Views  <span id="creating-views"></span><a href="#creating-views" class="hashlink">&para;</a></h2><p>As aforementioned, a view is simply a PHP script mixed with HTML and PHP code. The following is the view
that presents a login form. As you can see, PHP code is used to generate the dynamic content, such as the
page title and the form, while HTML code organizes them into a presentable HTML page.</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">helpers</span>\<span class="hljs-title">Html</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">widgets</span>\<span class="hljs-title">ActiveForm</span>;

<span class="hljs-comment">/* <span class="hljs-doctag">@var</span> $this yii\web\View */</span>
<span class="hljs-comment">/* <span class="hljs-doctag">@var</span> $form yii\widgets\ActiveForm */</span>
<span class="hljs-comment">/* <span class="hljs-doctag">@var</span> $model app\models\LoginForm */</span>

<span class="hljs-variable">$this</span>-&gt;title = <span class="hljs-string">'Login'</span>;
<span class="hljs-preprocessor">?&gt;</span>
&lt;h1&gt;<span class="hljs-preprocessor">&lt;?</span>= Html::encode(<span class="hljs-variable">$this</span>-&gt;title) <span class="hljs-preprocessor">?&gt;</span>&lt;/h1&gt;

&lt;p&gt;Please fill out the following fields to login:&lt;/p&gt;

<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$form</span> = ActiveForm::begin(); <span class="hljs-preprocessor">?&gt;</span>
    <span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$form</span>-&gt;field(<span class="hljs-variable">$model</span>, <span class="hljs-string">'username'</span>) <span class="hljs-preprocessor">?&gt;</span>
    <span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$form</span>-&gt;field(<span class="hljs-variable">$model</span>, <span class="hljs-string">'password'</span>)-&gt;passwordInput() <span class="hljs-preprocessor">?&gt;</span>
    <span class="hljs-preprocessor">&lt;?</span>= Html::submitButton(<span class="hljs-string">'Login'</span>) <span class="hljs-preprocessor">?&gt;</span>
<span class="hljs-preprocessor">&lt;?php</span> ActiveForm::end(); <span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<p>Within a view, you can access <code>$this</code> which refers to the <a href="./yii-web-view.html">view component</a> managing
and rendering this view template.</p>
<p>Besides <code>$this</code>, there may be other predefined variables in a view, such as <code>$model</code> in the above
example. These variables represent the data that are <em>pushed</em> into the view by <a href="guide-structure-controllers.html">controllers</a>
or other objects which trigger the <a href="#rendering-views">view rendering</a>.</p>
<blockquote class="tip"><p><strong>Tip: </strong>The predefined variables are listed in a comment block at beginning of a view so that they can
  be recognized by IDEs. It is also a good way of documenting your views.</p>
</blockquote>
<h3>Security  <span id="security"></span><a href="#security" class="hashlink">&para;</a></h3><p>When creating views that generate HTML pages, it is important that you encode and/or filter the data coming
from end users before presenting them. Otherwise, your application may be subject to
<a href="http://en.wikipedia.org/wiki/Cross-site_scripting">cross-site scripting</a> attacks.</p>
<p>To display a plain text, encode it first by calling <a href="./yii-helpers-basehtml.html#encode()-detail">yii\helpers\Html::encode()</a>. For example, the following code
encodes the user name before displaying it:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">helpers</span>\<span class="hljs-title">Html</span>;
<span class="hljs-preprocessor">?&gt;</span>

&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span>="<span class="hljs-title">username</span>"&gt;
    &lt;?= <span class="hljs-title">Html</span>::<span class="hljs-title">encode</span>($<span class="hljs-title">user</span>-&gt;<span class="hljs-title">name</span>) ?&gt;
&lt;/<span class="hljs-title">div</span>&gt;
</span></code></pre>
<p>To display HTML content, use <a href="./yii-helpers-htmlpurifier.html">yii\helpers\HtmlPurifier</a> to filter the content first. For example, the following
code filters the post content before displaying it:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">helpers</span>\<span class="hljs-title">HtmlPurifier</span>;
<span class="hljs-preprocessor">?&gt;</span>

&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span>="<span class="hljs-title">post</span>"&gt;
    &lt;?= <span class="hljs-title">HtmlPurifier</span>::<span class="hljs-title">process</span>($<span class="hljs-title">post</span>-&gt;<span class="hljs-title">text</span>) ?&gt;
&lt;/<span class="hljs-title">div</span>&gt;
</span></code></pre>
<blockquote class="tip"><p><strong>Tip: </strong>While HTMLPurifier does excellent job in making output safe, it is not fast. You should consider
  <a href="guide-caching-overview.html">caching</a> the filtering result if your application requires high performance.</p>
</blockquote>
<h3>Organizing Views  <span id="organizing-views"></span><a href="#organizing-views" class="hashlink">&para;</a></h3><p>Like <a href="guide-structure-controllers.html">controllers</a> and <a href="guide-structure-models.html">models</a>, there are conventions to organize views.</p>
<ul>
<li>For views rendered by a controller, they should be put under the directory <code>@app/views/ControllerID</code> by default,
where <code>ControllerID</code> refers to the <a href="guide-structure-controllers.html#routes">controller ID</a>. For example, if
the controller class is <code>PostController</code>, the directory would be <code>@app/views/post</code>; If it is <code>PostCommentController</code>,
the directory would be <code>@app/views/post-comment</code>. In case the controller belongs to a module, the directory
would be <code>views/ControllerID</code> under the <a href="./yii-base-module.html#$basePath-detail">module directory</a>.</li>
<li>For views rendered in a <a href="guide-structure-widgets.html">widget</a>, they should be put under the <code>WidgetPath/views</code> directory by
default, where <code>WidgetPath</code> stands for the directory containing the widget class file.</li>
<li>For views rendered by other objects, it is recommended that you follow the similar convention as that for widgets.</li>
</ul>
<p>You may customize these default view directories by overriding the <a href="./yii-base-viewcontextinterface.html#getViewPath()-detail">yii\base\ViewContextInterface::getViewPath()</a>
method of controllers or widgets.</p>
<h2>Rendering Views  <span id="rendering-views"></span><a href="#rendering-views" class="hashlink">&para;</a></h2><p>You can render views in <a href="guide-structure-controllers.html">controllers</a>, <a href="guide-structure-widgets.html">widgets</a>, or any
other places by calling view rendering methods. These methods share a similar signature shown as follows,</p>
<pre><code class="hljs php"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@param</span> string $view view name or file path, depending on the actual rendering method
 * <span class="hljs-doctag">@param</span> array $params the data to be passed to the view
 * <span class="hljs-doctag">@return</span> string rendering result
 */</span>
methodName(<span class="hljs-variable">$view</span>, <span class="hljs-variable">$params</span> = [])
</code></pre>
<h3>Rendering in Controllers  <span id="rendering-in-controllers"></span><a href="#rendering-in-controllers" class="hashlink">&para;</a></h3><p>Within <a href="guide-structure-controllers.html">controllers</a>, you may call the following controller methods to render views:</p>
<ul>
<li><a href="./yii-base-controller.html#render()-detail">render()</a>: renders a <a href="#named-views">named view</a> and applies a <a href="#layouts">layout</a>
to the rendering result.</li>
<li><a href="./yii-base-controller.html#renderPartial()-detail">renderPartial()</a>: renders a <a href="#named-views">named view</a> without any layout.</li>
<li><a href="./yii-web-controller.html#renderAjax()-detail">renderAjax()</a>: renders a <a href="#named-views">named view</a> without any layout,
and injects all registered JS/CSS scripts and files. It is usually used in response to AJAX Web requests.</li>
<li><a href="./yii-base-controller.html#renderFile()-detail">renderFile()</a>: renders a view specified in terms of a view file path or
<a href="guide-concept-aliases.html">alias</a>.</li>
<li><a href="./yii-base-controller.html#renderContent()-detail">renderContent()</a>: renders a static string by embedding it into
the currently applicable <a href="#layouts">layout</a>. This method is available since version 2.0.1.</li>
</ul>
<p>For example,</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">app</span>\<span class="hljs-title">controllers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">Yii</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">app</span>\<span class="hljs-title">models</span>\<span class="hljs-title">Post</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">web</span>\<span class="hljs-title">Controller</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">web</span>\<span class="hljs-title">NotFoundHttpException</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">actionView</span><span class="hljs-params">(<span class="hljs-variable">$id</span>)</span>
    </span>{
        <span class="hljs-variable">$model</span> = Post::findOne(<span class="hljs-variable">$id</span>);
        <span class="hljs-keyword">if</span> (<span class="hljs-variable">$model</span> === <span class="hljs-keyword">null</span>) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> NotFoundHttpException;
        }

        <span class="hljs-comment">// renders a view named "view" and applies a layout to it</span>
        <span class="hljs-keyword">return</span> <span class="hljs-variable">$this</span>-&gt;render(<span class="hljs-string">'view'</span>, [
            <span class="hljs-string">'model'</span> =&gt; <span class="hljs-variable">$model</span>,
        ]);
    }
}
</code></pre>
<h3>Rendering in Widgets  <span id="rendering-in-widgets"></span><a href="#rendering-in-widgets" class="hashlink">&para;</a></h3><p>Within <a href="guide-structure-widgets.html">widgets</a>, you may call the following widget methods to render views.</p>
<ul>
<li><a href="./yii-base-widget.html#render()-detail">render()</a>: renders a <a href="#named-views">named view</a>.</li>
<li><a href="./yii-base-widget.html#renderFile()-detail">renderFile()</a>: renders a view specified in terms of a view file path or
<a href="guide-concept-aliases.html">alias</a>.</li>
</ul>
<p>For example,</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">app</span>\<span class="hljs-title">components</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">base</span>\<span class="hljs-title">Widget</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">helpers</span>\<span class="hljs-title">Html</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ListWidget</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Widget</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-variable">$items</span> = [];

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">run</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-comment">// renders a view named "list"</span>
        <span class="hljs-keyword">return</span> <span class="hljs-variable">$this</span>-&gt;render(<span class="hljs-string">'list'</span>, [
            <span class="hljs-string">'items'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;items,
        ]);
    }
}
</code></pre>
<h3>Rendering in Views  <span id="rendering-in-views"></span><a href="#rendering-in-views" class="hashlink">&para;</a></h3><p>You can render a view within another view by calling one of the following methods provided by the <a href="./yii-base-view.html">view component</a>:</p>
<ul>
<li><a href="./yii-base-view.html#render()-detail">render()</a>: renders a <a href="#named-views">named view</a>.</li>
<li><a href="./yii-web-view.html#renderAjax()-detail">renderAjax()</a>: renders a <a href="#named-views">named view</a> and injects all registered
JS/CSS scripts and files. It is usually used in response to AJAX Web requests.</li>
<li><a href="./yii-base-view.html#renderFile()-detail">renderFile()</a>: renders a view specified in terms of a view file path or
<a href="guide-concept-aliases.html">alias</a>.</li>
</ul>
<p>For example, the following code in a view renders the <code>_overview.php</code> view file which is in the same directory
as the view being currently rendered. Remember that <code>$this</code> in a view refers to the <a href="./yii-base-view.html">view</a> component:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$this</span>-&gt;render(<span class="hljs-string">'_overview'</span>) <span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<h3>Rendering in Other Places  <span id="rendering-in-other-places"></span><a href="#rendering-in-other-places" class="hashlink">&para;</a></h3><p>In any place, you can get access to the <a href="./yii-base-view.html">view</a> application component by the expression
<code>Yii::$app-&gt;view</code> and then call its aforementioned methods to render a view. For example,</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">// displays the view file "@app/views/site/license.php"</span>
<span class="hljs-keyword">echo</span> \Yii::<span class="hljs-variable">$app</span>-&gt;view-&gt;renderFile(<span class="hljs-string">'@app/views/site/license.php'</span>);
</code></pre>
<h3>Named Views  <span id="named-views"></span><a href="#named-views" class="hashlink">&para;</a></h3><p>When you render a view, you can specify the view using either a view name or a view file path/alias. In most cases,
you would use the former because it is more concise and flexible. We call views specified using names as <em>named views</em>.</p>
<p>A view name is resolved into the corresponding view file path according to the following rules:</p>
<ul>
<li>A view name may omit the file extension name. In this case, <code>.php</code> will be used as the extension. For example,
the view name <code>about</code> corresponds to the file name <code>about.php</code>.</li>
<li>If the view name starts with double slashes <code>//</code>, the corresponding view file path would be <code>@app/views/ViewName</code>.
That is, the view is looked for under the <a href="./yii-base-module.html#$viewPath-detail">application's view path</a>.
For example, <code>//site/about</code> will be resolved into <code>@app/views/site/about.php</code>.</li>
<li>If the view name starts with a single slash <code>/</code>, the view file path is formed by prefixing the view name
with the <a href="./yii-base-module.html#$viewPath-detail">view path</a> of the currently active <a href="guide-structure-modules.html">module</a>.
If there is no active module, <code>@app/views/ViewName</code> will be used. For example, <code>/user/create</code> will be resolved into
<code>@app/modules/user/views/user/create.php</code>, if the currently active module is <code>user</code>. If there is no active module,
the view file path would be <code>@app/views/user/create.php</code>.</li>
<li>If the view is rendered with a <a href="./yii-base-view.html#$context-detail">context</a> and the context implements <a href="./yii-base-viewcontextinterface.html">yii\base\ViewContextInterface</a>,
the view file path is formed by prefixing the <a href="./yii-base-viewcontextinterface.html#getViewPath()-detail">view path</a> of the
context to the view name. This mainly applies to the views rendered within controllers and widgets. For example,
<code>about</code> will be resolved into <code>@app/views/site/about.php</code> if the context is the controller <code>SiteController</code>.</li>
<li>If a view is rendered within another view, the directory containing the other view file will be prefixed to
the new view name to form the actual view file path. For example, <code>item</code> will be resolved into <code>@app/views/post/item.php</code>
if it is being rendered in the view <code>@app/views/post/index.php</code>.</li>
</ul>
<p>According to the above rules, calling <code>$this-&gt;render('view')</code> in a controller <code>app\controllers\PostController</code> will
actually render the view file <code>@app/views/post/view.php</code>, while calling <code>$this-&gt;render('_overview')</code> in that view
will render the view file <code>@app/views/post/_overview.php</code>.</p>
<h3>Accessing Data in Views  <span id="accessing-data-in-views"></span><a href="#accessing-data-in-views" class="hashlink">&para;</a></h3><p>There are two approaches to access data within a view: push and pull.</p>
<p>By passing the data as the second parameter to the view rendering methods, you are using the push approach.
The data should be represented as an array of name-value pairs. When the view is being rendered, the PHP
<code>extract()</code> function will be called on this array so that the array is extracted into variables in the view.
For example, the following view rendering code in a controller will push two variables to the <code>report</code> view:
<code>$foo = 1</code> and <code>$bar = 2</code>.</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">echo</span> <span class="hljs-variable">$this</span>-&gt;render(<span class="hljs-string">'report'</span>, [
    <span class="hljs-string">'foo'</span> =&gt; <span class="hljs-number">1</span>,
    <span class="hljs-string">'bar'</span> =&gt; <span class="hljs-number">2</span>,
]);
</code></pre>
<p>The pull approach actively retrieves data from the <a href="./yii-base-view.html">view component</a> or other objects accessible
in views (e.g. <code>Yii::$app</code>). Using the code below as an example, within the view you can get the controller object
by the expression <code>$this-&gt;context</code>. And as a result, it is possible for you to access any properties or methods
of the controller in the <code>report</code> view, such as the controller ID shown in the following:</p>
<pre><code class="hljs php language-php">The controller ID is: <span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$this</span>-&gt;context-&gt;id <span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<p>The push approach is usually the preferred way of accessing data in views, because it makes views less dependent
on context objects. Its drawback is that you need to manually build the data array all the time, which could
become tedious and error prone if a view is shared and rendered in different places.</p>
<h3>Sharing Data among Views  <span id="sharing-data-among-views"></span><a href="#sharing-data-among-views" class="hashlink">&para;</a></h3><p>The <a href="./yii-base-view.html">view component</a> provides the <a href="./yii-base-view.html#$params-detail">params</a> property that you can use
to share data among views.</p>
<p>For example, in an <code>about</code> view, you can have the following code which specifies the current segment of the
breadcrumbs.</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$this</span>-&gt;params[<span class="hljs-string">'breadcrumbs'</span>][] = <span class="hljs-string">'About Us'</span>;
</code></pre>
<p>Then, in the <a href="#layouts">layout</a> file, which is also a view, you can display the breadcrumbs using the data
passed along <a href="./yii-base-view.html#$params-detail">params</a>:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?</span>= yii\widgets\Breadcrumbs::widget([
    <span class="hljs-string">'links'</span> =&gt; <span class="hljs-keyword">isset</span>(<span class="hljs-variable">$this</span>-&gt;params[<span class="hljs-string">'breadcrumbs'</span>]) ? <span class="hljs-variable">$this</span>-&gt;params[<span class="hljs-string">'breadcrumbs'</span>] : [],
]) <span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<h2>Layouts  <span id="layouts"></span><a href="#layouts" class="hashlink">&para;</a></h2><p>Layouts are a special type of views that represent the common parts of multiple views. For example, the pages
for most Web applications share the same page header and footer. While you can repeat the same page header and footer
in every view, a better way is to do this once in a layout and embed the rendering result of a content view at
an appropriate place in the layout.</p>
<h3>Creating Layouts  <span id="creating-layouts"></span><a href="#creating-layouts" class="hashlink">&para;</a></h3><p>Because layouts are also views, they can be created in the similar way as normal views. By default, layouts
are stored in the directory <code>@app/views/layouts</code>. For layouts used within a <a href="guide-structure-modules.html">module</a>,
they should be stored in the <code>views/layouts</code> directory under the <a href="./yii-base-module.html#$basePath-detail">module directory</a>.
You may customize the default layout directory by configuring the <a href="./yii-base-module.html#$layoutPath-detail">yii\base\Module::$layoutPath</a> property of
the application or modules.</p>
<p>The following example shows how a layout looks like. Note that for illustrative purpose, we have greatly simplified
the code in the layout. In practice, you may want to add more content to it, such as head tags, main menu, etc.</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">helpers</span>\<span class="hljs-title">Html</span>;

<span class="hljs-comment">/* <span class="hljs-doctag">@var</span> $this yii\web\View */</span>
<span class="hljs-comment">/* <span class="hljs-doctag">@var</span> $content string */</span>
<span class="hljs-preprocessor">?&gt;</span>
<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$this</span>-&gt;beginPage() <span class="hljs-preprocessor">?&gt;</span>
&lt;!DOCTYPE html&gt;
&lt;html lang=<span class="hljs-string">"en"</span>&gt;
&lt;head&gt;
    &lt;meta charset=<span class="hljs-string">"UTF-8"</span>/&gt;
    <span class="hljs-preprocessor">&lt;?</span>= Html::csrfMetaTags() <span class="hljs-preprocessor">?&gt;</span>
    &lt;title&gt;<span class="hljs-preprocessor">&lt;?</span>= Html::encode(<span class="hljs-variable">$this</span>-&gt;title) <span class="hljs-preprocessor">?&gt;</span>&lt;/title&gt;
    <span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$this</span>-&gt;head() <span class="hljs-preprocessor">?&gt;</span>
&lt;/head&gt;
&lt;body&gt;
<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$this</span>-&gt;beginBody() <span class="hljs-preprocessor">?&gt;</span>
    &lt;header&gt;My Company&lt;/header&gt;
    <span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$content</span> <span class="hljs-preprocessor">?&gt;</span>
    &lt;footer&gt;&amp;copy; <span class="hljs-number">2014</span> by My Company&lt;/footer&gt;
<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$this</span>-&gt;endBody() <span class="hljs-preprocessor">?&gt;</span>
&lt;/body&gt;
&lt;/html&gt;
<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$this</span>-&gt;endPage() <span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<p>As you can see, the layout generates the HTML tags that are common to all pages. Within the <code>&lt;body&gt;</code> section,
the layout echoes the <code>$content</code> variable which represents the rendering result of content views and is pushed
into the layout when <a href="./yii-base-controller.html#render()-detail">yii\base\Controller::render()</a> is called.</p>
<p>Most layouts should call the following methods like shown in the above code. These methods mainly trigger events
about the rendering process so that scripts and tags registered in other places can be properly injected into
the places where these methods are called.</p>
<ul>
<li><a href="./yii-base-view.html#beginPage()-detail">beginPage()</a>: This method should be called at the very beginning of the layout.
It triggers the <a href="./yii-base-view.html#EVENT_BEGIN_PAGE-detail">EVENT_BEGIN_PAGE</a> event which indicates the beginning of a page.</li>
<li><a href="./yii-base-view.html#endPage()-detail">endPage()</a>: This method should be called at the end of the layout.
It triggers the <a href="./yii-base-view.html#EVENT_END_PAGE-detail">EVENT_END_PAGE</a> event which indicates the end of a page.</li>
<li><a href="./yii-web-view.html#head()-detail">head()</a>: This method should be called within the <code>&lt;head&gt;</code> section of an HTML page.
It generates a placeholder which will be replaced with the registered head HTML code (e.g. link tags, meta tags)
when a page finishes rendering.</li>
<li><a href="./yii-web-view.html#beginBody()-detail">beginBody()</a>: This method should be called at the beginning of the <code>&lt;body&gt;</code> section.
It triggers the <a href="./yii-web-view.html#EVENT_BEGIN_BODY-detail">EVENT_BEGIN_BODY</a> event and generates a placeholder which will
be replaced by the registered HTML code (e.g. JavaScript) targeted at the body begin position.</li>
<li><a href="./yii-web-view.html#endBody()-detail">endBody()</a>: This method should be called at the end of the <code>&lt;body&gt;</code> section.
It triggers the <a href="./yii-web-view.html#EVENT_END_BODY-detail">EVENT_END_BODY</a> event and generates a placeholder which will
be replaced by the registered HTML code (e.g. JavaScript) targeted at the body end position.</li>
</ul>
<h3>Accessing Data in Layouts  <span id="accessing-data-in-layouts"></span><a href="#accessing-data-in-layouts" class="hashlink">&para;</a></h3><p>Within a layout, you have access to two predefined variables: <code>$this</code> and <code>$content</code>. The former refers to
the <a href="./yii-base-view.html">view</a> component, like in normal views, while the latter contains the rendering result of a content
view which is rendered by calling the <a href="./yii-base-controller.html#render()-detail">render()</a> method in controllers.</p>
<p>If you want to access other data in layouts, you have to use the pull method as described in
the <a href="#accessing-data-in-views">Accessing Data in Views</a> subsection. If you want to pass data from a content view
to a layout, you may use the method described in the <a href="#sharing-data-among-views">Sharing Data among Views</a> subsection.</p>
<h3>Using Layouts  <span id="using-layouts"></span><a href="#using-layouts" class="hashlink">&para;</a></h3><p>As described in the <a href="#rendering-in-controllers">Rendering in Controllers</a> subsection, when you render a view
by calling the <a href="./yii-base-controller.html#render()-detail">render()</a> method in a controller, a layout will be applied
to the rendering result. By default, the layout <code>@app/views/layouts/main.php</code> will be used. </p>
<p>You may use a different layout by configuring either <a href="./yii-base-application.html#$layout-detail">yii\base\Application::$layout</a> or <a href="./yii-base-controller.html#$layout-detail">yii\base\Controller::$layout</a>.
The former governs the layout used by all controllers, while the latter overrides the former for individual controllers.
For example, the following code makes the <code>post</code> controller to use <code>@app/views/layouts/post.php</code> as the layout
when rendering its views. Other controllers, assuming their <code>layout</code> property is untouched, will still use the default
<code>@app/views/layouts/main.php</code> as the layout.</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">app</span>\<span class="hljs-title">controllers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">web</span>\<span class="hljs-title">Controller</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-variable">$layout</span> = <span class="hljs-string">'post'</span>;
    
    <span class="hljs-comment">// ...</span>
}
</code></pre>
<p>For controllers belonging to a module, you may also configure the module's <a href="./yii-base-module.html#$layout-detail">layout</a> property to
use a particular layout for these controllers. </p>
<p>Because the <code>layout</code> property may be configured at different levels (controllers, modules, application),
behind the scene Yii takes two steps to determine what is the actual layout file being used for a particular controller.</p>
<p>In the first step, it determines the layout value and the context module:</p>
<ul>
<li>If the <a href="./yii-base-controller.html#$layout-detail">yii\base\Controller::$layout</a> property of the controller is not null, use it as the layout value and
the <a href="./yii-base-controller.html#$module-detail">module</a> of the controller as the context module.</li>
<li>If <a href="./yii-base-controller.html#$layout-detail">layout</a> is null, search through all ancestor modules (including the application itself) of the controller and 
find the first module whose <a href="./yii-base-module.html#$layout-detail">layout</a> property is not null. Use that module and
its <a href="./yii-base-module.html#$layout-detail">layout</a> value as the context module and the chosen layout value.
If such a module cannot be found, it means no layout will be applied.</li>
</ul>
<p>In the second step, it determines the actual layout file according to the layout value and the context module
determined in the first step. The layout value can be:</p>
<ul>
<li>a path alias (e.g. <code>@app/views/layouts/main</code>).</li>
<li>an absolute path (e.g. <code>/main</code>): the layout value starts with a slash. The actual layout file will be
looked for under the application's <a href="./yii-base-module.html#$layoutPath-detail">layout path</a> which defaults to
<code>@app/views/layouts</code>.</li>
<li>a relative path (e.g. <code>main</code>): the actual layout file will be looked for under the context module's
<a href="./yii-base-module.html#$layoutPath-detail">layout path</a> which defaults to the <code>views/layouts</code> directory under the
<a href="./yii-base-module.html#$basePath-detail">module directory</a>.</li>
<li>the boolean value <code>false</code>: no layout will be applied.</li>
</ul>
<p>If the layout value does not contain a file extension, it will use the default one <code>.php</code>.</p>
<h3>Nested Layouts  <span id="nested-layouts"></span><a href="#nested-layouts" class="hashlink">&para;</a></h3><p>Sometimes you may want to nest one layout in another. For example, in different sections of a Web site, you
want to use different layouts, while all these layouts share the same basic layout that generates the overall
HTML5 page structure. You can achieve this goal by calling <a href="./yii-base-view.html#beginContent()-detail">beginContent()</a> and
<a href="./yii-base-view.html#endContent()-detail">endContent()</a> in the child layouts like the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$this</span>-&gt;beginContent(<span class="hljs-string">'@app/views/layouts/base.php'</span>); <span class="hljs-preprocessor">?&gt;</span>

...child layout content here...

<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$this</span>-&gt;endContent(); <span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<p>As shown above, the child layout content should be enclosed within <a href="./yii-base-view.html#beginContent()-detail">beginContent()</a> and
<a href="./yii-base-view.html#endContent()-detail">endContent()</a>. The parameter passed to <a href="./yii-base-view.html#beginContent()-detail">beginContent()</a>
specifies what is the parent layout. It can be either a layout file or alias.</p>
<p>Using the above approach, you can nest layouts in more than one levels.</p>
<h3>Using Blocks  <span id="using-blocks"></span><a href="#using-blocks" class="hashlink">&para;</a></h3><p>Blocks allow you to specify the view content in one place while displaying it in another. They are often used together
with layouts. For example, you can define a block in a content view and display it in the layout.</p>
<p>You call <a href="./yii-base-view.html#beginBlock()-detail">beginBlock()</a> and <a href="./yii-base-view.html#endBlock()-detail">endBlock()</a> to define a block.
The block can then be accessed via <code>$view-&gt;blocks[$blockID]</code>, where <code>$blockID</code> stands for a unique ID that you assign
to the block when defining it.</p>
<p>The following example shows how you can use blocks to customize specific parts of a layout in a content view.</p>
<p>First, in a content view, define one or multiple blocks:</p>
<pre><code class="hljs php language-php">...

<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$this</span>-&gt;beginBlock(<span class="hljs-string">'block1'</span>); <span class="hljs-preprocessor">?&gt;</span>

...content of block1...

<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$this</span>-&gt;endBlock(); <span class="hljs-preprocessor">?&gt;</span>

...

<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$this</span>-&gt;beginBlock(<span class="hljs-string">'block3'</span>); <span class="hljs-preprocessor">?&gt;</span>

...content of block3...

<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-variable">$this</span>-&gt;endBlock(); <span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<p>Then, in the layout view, render the blocks if they are available, or display some default content if a block is
not defined.</p>
<pre><code class="hljs php language-php">...
<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>(<span class="hljs-variable">$this</span>-&gt;blocks[<span class="hljs-string">'block1'</span>])): <span class="hljs-preprocessor">?&gt;</span>
    <span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$this</span>-&gt;blocks[<span class="hljs-string">'block1'</span>] <span class="hljs-preprocessor">?&gt;</span>
<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-keyword">else</span>: <span class="hljs-preprocessor">?&gt;</span>
    ... <span class="hljs-keyword">default</span> content <span class="hljs-keyword">for</span> block1 ...
<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-keyword">endif</span>; <span class="hljs-preprocessor">?&gt;</span>

...

<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>(<span class="hljs-variable">$this</span>-&gt;blocks[<span class="hljs-string">'block2'</span>])): <span class="hljs-preprocessor">?&gt;</span>
    <span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$this</span>-&gt;blocks[<span class="hljs-string">'block2'</span>] <span class="hljs-preprocessor">?&gt;</span>
<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-keyword">else</span>: <span class="hljs-preprocessor">?&gt;</span>
    ... <span class="hljs-keyword">default</span> content <span class="hljs-keyword">for</span> block2 ...
<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-keyword">endif</span>; <span class="hljs-preprocessor">?&gt;</span>

...

<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>(<span class="hljs-variable">$this</span>-&gt;blocks[<span class="hljs-string">'block3'</span>])): <span class="hljs-preprocessor">?&gt;</span>
    <span class="hljs-preprocessor">&lt;?</span>= <span class="hljs-variable">$this</span>-&gt;blocks[<span class="hljs-string">'block3'</span>] <span class="hljs-preprocessor">?&gt;</span>
<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-keyword">else</span>: <span class="hljs-preprocessor">?&gt;</span>
    ... <span class="hljs-keyword">default</span> content <span class="hljs-keyword">for</span> block3 ...
<span class="hljs-preprocessor">&lt;?php</span> <span class="hljs-keyword">endif</span>; <span class="hljs-preprocessor">?&gt;</span>
...
</code></pre>
<h2>Using View Components  <span id="using-view-components"></span><a href="#using-view-components" class="hashlink">&para;</a></h2><p><a href="./yii-base-view.html">View components</a> provides many view-related features. While you can get view components
by creating individual instances of <a href="./yii-base-view.html">yii\base\View</a> or its child class, in most cases you will mainly use
the <code>view</code> application component. You can configure this component in <a href="guide-structure-applications.html#application-configurations">application configurations</a>
like the following:</p>
<pre><code class="hljs php language-php">[
    <span class="hljs-comment">// ...</span>
    <span class="hljs-string">'components'</span> =&gt; [
        <span class="hljs-string">'view'</span> =&gt; [
            <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'app\components\View'</span>,
        ],
        <span class="hljs-comment">// ...</span>
    ],
]
</code></pre>
<p>View components provide the following useful view-related features, each described in more details in a separate section:</p>
<ul>
<li><a href="guide-output-theming.html">theming</a>: allows you to develop and change the theme for your Web site.</li>
<li><a href="guide-caching-fragment.html">fragment caching</a>: allows you to cache a fragment within a Web page.</li>
<li><a href="guide-output-client-scripts.html">client script handling</a>: supports CSS and JavaScript registration and rendering.</li>
<li><a href="guide-structure-assets.html">asset bundle handling</a>: supports registering and rendering of <a href="guide-structure-assets.html">asset bundles</a>.</li>
<li><a href="guide-tutorial-template-engines.html">alternative template engines</a>: allows you to use other template engines, such as
<a href="http://twig.sensiolabs.org/">Twig</a>, <a href="http://www.smarty.net/">Smarty</a>.</li>
</ul>
<p>You may also frequently use the following minor yet useful features when you are developing Web pages.</p>
<h3>Setting Page Titles  <span id="setting-page-titles"></span><a href="#setting-page-titles" class="hashlink">&para;</a></h3><p>Every Web page should have a title. Normally the title tag is being displayed in a <a href="#layouts">layout</a>. However, in practice
the title is often determined in content views rather than layouts. To solve this problem, <a href="./yii-web-view.html">yii\web\View</a> provides
the <a href="./yii-web-view.html#$title-detail">title</a> property for you to pass the title information from content views to layouts.</p>
<p>To make use of this feature, in each content view, you can set the page title like the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-variable">$this</span>-&gt;title = <span class="hljs-string">'My page title'</span>;
<span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<p>Then in the layout, make sure you have the following code in the <code>&lt;head&gt;</code> section:</p>
<pre><code class="hljs php language-php">&lt;title&gt;<span class="hljs-preprocessor">&lt;?</span>= Html::encode(<span class="hljs-variable">$this</span>-&gt;title) <span class="hljs-preprocessor">?&gt;</span>&lt;/title&gt;
</code></pre>
<h3>Registering Meta Tags  <span id="registering-meta-tags"></span><a href="#registering-meta-tags" class="hashlink">&para;</a></h3><p>Web pages usually need to generate various meta tags needed by different parties. Like page titles, meta tags
appear in the <code>&lt;head&gt;</code> section and are usually generated in layouts.</p>
<p>If you want to specify what meta tags to generate in content views, you can call <a href="./yii-web-view.html#registerMetaTag()-detail">yii\web\View::registerMetaTag()</a>
in a content view, like the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-variable">$this</span>-&gt;registerMetaTag([<span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'keywords'</span>, <span class="hljs-string">'content'</span> =&gt; <span class="hljs-string">'yii, framework, php'</span>]);
<span class="hljs-preprocessor">?&gt;</span>
</code></pre>
<p>The above code will register a "keywords" meta tag with the view component. The registered meta tag is
rendered after the layout finishes rendering. The following HTML code will be generated and inserted
at the place where you call <a href="./yii-web-view.html#head()-detail">yii\web\View::head()</a> in the layout:</p>
<pre><code class="hljs php language-php">&lt;meta name=<span class="hljs-string">"keywords"</span> content=<span class="hljs-string">"yii, framework, php"</span>&gt;
</code></pre>
<p>Note that if you call <a href="./yii-web-view.html#registerMetaTag()-detail">yii\web\View::registerMetaTag()</a> multiple times, it will register multiple meta tags,
regardless whether the meta tags are the same or not.</p>
<p>To make sure there is only a single instance of a meta tag type, you can specify a key as a second parameter when calling the method.
For example, the following code registers two "description" meta tags. However, only the second one will be rendered.</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$this</span>-&gt;registerMetaTag([<span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'description'</span>, <span class="hljs-string">'content'</span> =&gt; <span class="hljs-string">'This is my cool website made with Yii!'</span>], <span class="hljs-string">'description'</span>);
<span class="hljs-variable">$this</span>-&gt;registerMetaTag([<span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'description'</span>, <span class="hljs-string">'content'</span> =&gt; <span class="hljs-string">'This website is about funny raccoons.'</span>], <span class="hljs-string">'description'</span>);
</code></pre>
<h3>Registering Link Tags  <span id="registering-link-tags"></span><a href="#registering-link-tags" class="hashlink">&para;</a></h3><p>Like <a href="#registering-meta-tags">meta tags</a>, link tags are useful in many cases, such as customizing favicon, pointing to
RSS feed or delegating OpenID to another server. You can work with link tags in the similar way as meta tags
by using <a href="./yii-web-view.html#registerLinkTag()-detail">yii\web\View::registerLinkTag()</a>. For example, in a content view, you can register a link tag like follows,</p>
<pre><code class="hljs php language-php"><span class="hljs-variable">$this</span>-&gt;registerLinkTag([
    <span class="hljs-string">'title'</span> =&gt; <span class="hljs-string">'Live News for Yii'</span>,
    <span class="hljs-string">'rel'</span> =&gt; <span class="hljs-string">'alternate'</span>,
    <span class="hljs-string">'type'</span> =&gt; <span class="hljs-string">'application/rss+xml'</span>,
    <span class="hljs-string">'href'</span> =&gt; <span class="hljs-string">'http://www.yiiframework.com/rss.xml/'</span>,
]);
</code></pre>
<p>The code above will result in</p>
<pre><code class="hljs xml language-html"><span class="hljs-tag">&lt;<span class="hljs-title">link</span> <span class="hljs-attribute">title</span>=<span class="hljs-value">"Live News for Yii"</span> <span class="hljs-attribute">rel</span>=<span class="hljs-value">"alternate"</span> <span class="hljs-attribute">type</span>=<span class="hljs-value">"application/rss+xml"</span> <span class="hljs-attribute">href</span>=<span class="hljs-value">"http://www.yiiframework.com/rss.xml/"</span>&gt;</span>
</code></pre>
<p>Similar as <a href="./yii-web-view.html#registerMetaTag()-detail">registerMetaTags()</a>, you can specify a key when calling
<a href="./yii-web-view.html#registerLinkTag()-detail">registerLinkTag()</a> to avoid generating repeated link tags.</p>
<h2>View Events  <span id="view-events"></span><a href="#view-events" class="hashlink">&para;</a></h2><p><a href="./yii-base-view.html">View components</a> trigger several events during the view rendering process. You may respond
to these events to inject content into views or process the rendering results before they are sent to end users.</p>
<ul>
<li><a href="./yii-base-view.html#EVENT_BEFORE_RENDER-detail">EVENT_BEFORE_RENDER</a>: triggered at the beginning of rendering a file
in a controller. Handlers of this event may set <a href="./yii-base-viewevent.html#$isValid-detail">yii\base\ViewEvent::$isValid</a> to be false to cancel the rendering process.</li>
<li><a href="./yii-base-view.html#EVENT_AFTER_RENDER-detail">EVENT_AFTER_RENDER</a>: triggered after rendering a file by the call of <a href="./yii-base-view.html#afterRender()-detail">yii\base\View::afterRender()</a>.
Handlers of this event may obtain the rendering result through <a href="./yii-base-viewevent.html#$output-detail">yii\base\ViewEvent::$output</a> and may modify
this property to change the rendering result.</li>
<li><a href="./yii-base-view.html#EVENT_BEGIN_PAGE-detail">EVENT_BEGIN_PAGE</a>: triggered by the call of <a href="./yii-base-view.html#beginPage()-detail">yii\base\View::beginPage()</a> in layouts.</li>
<li><a href="./yii-base-view.html#EVENT_END_PAGE-detail">EVENT_END_PAGE</a>: triggered by the call of <a href="./yii-base-view.html#endPage()-detail">yii\base\View::endPage()</a> in layouts.</li>
<li><a href="./yii-web-view.html#EVENT_BEGIN_BODY-detail">EVENT_BEGIN_BODY</a>: triggered by the call of <a href="./yii-web-view.html#beginBody()-detail">yii\web\View::beginBody()</a> in layouts.</li>
<li><a href="./yii-web-view.html#EVENT_END_BODY-detail">EVENT_END_BODY</a>: triggered by the call of <a href="./yii-web-view.html#endBody()-detail">yii\web\View::endBody()</a> in layouts.</li>
</ul>
<p>For example, the following code injects the current date at the end of the page body:</p>
<pre><code class="hljs php language-php">\Yii::<span class="hljs-variable">$app</span>-&gt;view-&gt;on(View::EVENT_END_BODY, <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">echo</span> date(<span class="hljs-string">'Y-m-d'</span>);
});
</code></pre>
<h2>Rendering Static Pages  <span id="rendering-static-pages"></span><a href="#rendering-static-pages" class="hashlink">&para;</a></h2><p>Static pages refer to those Web pages whose main content are mostly static without the need of accessing
dynamic data pushed from controllers.</p>
<p>You can output static pages by putting their code in the view, and then using the code like the following in a controller:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">actionAbout</span><span class="hljs-params">()</span>
</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-variable">$this</span>-&gt;render(<span class="hljs-string">'about'</span>);
}
</code></pre>
<p>If a Web site contains many static pages, it would be very tedious repeating the similar code many times.
To solve this problem, you may introduce a <a href="guide-structure-controllers.html#standalone-actions">standalone action</a>
called <a href="./yii-web-viewaction.html">yii\web\ViewAction</a> in a controller. For example,</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">namespace</span> <span class="hljs-title">app</span>\<span class="hljs-title">controllers</span>;

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">web</span>\<span class="hljs-title">Controller</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SiteController</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Controller</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">actions</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">return</span> [
            <span class="hljs-string">'page'</span> =&gt; [
                <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'yii\web\ViewAction'</span>,
            ],
        ];
    }
}
</code></pre>
<p>Now if you create a view named <code>about</code> under the directory <code>@app/views/site/pages</code>, you will be able to
display this view by the following URL:</p>
<pre><code class="hljs less"><span class="hljs-attribute">http</span>:<span class="hljs-comment">//localhost/index.php?r=site%2Fpage&amp;view=about</span>
</code></pre>
<p>The <code>GET</code> parameter <code>view</code> tells <a href="./yii-web-viewaction.html">yii\web\ViewAction</a> which view is requested. The action will then look
for this view under the directory <code>@app/views/site/pages</code>. You may configure <a href="./yii-web-viewaction.html#$viewPrefix-detail">yii\web\ViewAction::$viewPrefix</a>
to change the directory for searching these views.</p>
<h2>Best Practices  <span id="best-practices"></span><a href="#best-practices" class="hashlink">&para;</a></h2><p>Views are responsible for presenting models in the format that end users desire. In general, views</p>
<ul>
<li>should mainly contain presentational code, such as HTML, and simple PHP code to traverse, format and render data.</li>
<li>should not contain code that performs DB queries. Such code should be done in models.</li>
<li>should avoid direct access to request data, such as <code>$_GET</code>, <code>$_POST</code>. This belongs to controllers.
If request data is needed, they should be pushed into views by controllers.</li>
<li>may read model properties, but should not modify them.</li>
</ul>
<p>To make views more manageable, avoid creating views that are too complex or contain too much redundant code.
You may use the following techniques to achieve this goal:</p>
<ul>
<li>use <a href="#layouts">layouts</a> to represent common presentational sections (e.g. page header, footer).</li>
<li>divide a complicated view into several smaller ones. The smaller views can be rendered and assembled into a bigger
one using the rendering methods that we have described.</li>
<li>create and use <a href="guide-structure-widgets.html">widgets</a> as building blocks of views.</li>
<li>create and use helper classes to transform and format data in views.</li>
</ul>
        <div class="toplink"><a href="#" class="h1" title="go to top"><span class="glyphicon glyphicon-arrow-up"></a></div>
    </div>
</div>


</div>

<footer class="footer">
        <p class="pull-right"><small>Page generated on Sat, 09 Jul 2016 12:16:30 +0000</small></p>
    Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a></footer>

<script type="text/javascript">jQuery(document).ready(function () {
    var shiftWindow = function () { scrollBy(0, -50) };
    if (location.hash) setTimeout(shiftWindow, 1);
    window.addEventListener("hashchange", shiftWindow);
var element = document.createElement("script");
element.src = "./jssearch.index.js";
document.body.appendChild(element);

var searchBox = $('#searchbox');

// search when typing in search field
searchBox.on("keyup", function(event) {
    var query = $(this).val();

    if (query == '' || event.which == 27) {
        $('#search-resultbox').hide();
        return;
    } else if (event.which == 13) {
        var selectedLink = $('#search-resultbox a.selected');
        if (selectedLink.length != 0) {
            document.location = selectedLink.attr('href');
            return;
        }
    } else if (event.which == 38 || event.which == 40) {
        $('#search-resultbox').show();

        var selected = $('#search-resultbox a.selected');
        if (selected.length == 0) {
            $('#search-results').find('a').first().addClass('selected');
        } else {
            var next;
            if (event.which == 40) {
                next = selected.parent().next().find('a').first();
            } else {
                next = selected.parent().prev().find('a').first();
            }
            if (next.length != 0) {
                var resultbox = $('#search-results');
                var position = next.position();

//              TODO scrolling is buggy and jumps around
//                resultbox.scrollTop(Math.floor(position.top));
//                console.log(position.top);

                selected.removeClass('selected');
                next.addClass('selected');
            }
        }

        return;
    }
    $('#search-resultbox').show();
    $('#search-results').html('<li><span class="no-results">No results</span></li>');

    var result = jssearch.search(query);

    if (result.length > 0) {
        var i = 0;
        var resHtml = '';

        for (var key in result) {
            if (i++ > 20) {
                break;
            }
            resHtml = resHtml +
            '<li><a href="' + result[key].file.u.substr(3) +'"><span class="title">' + result[key].file.t + '</span>' +
            '<span class="description">' + result[key].file.d + '</span></a></li>';
        }
        $('#search-results').html(resHtml);
    }
});

// hide the search results on ESC
$(document).on("keyup", function(event) { if (event.which == 27) { $('#search-resultbox').hide(); } });
// hide search results on click to document
$(document).bind('click', function (e) { $('#search-resultbox').hide(); });
// except the following:
searchBox.bind('click', function(e) { e.stopPropagation(); });
$('#search-resultbox').bind('click', function(e) { e.stopPropagation(); });

});</script></body>
</html>
